#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>        /* For mode constants */
#include <sys/types.h>
#include <fcntl.h>           /* For O_* constants */
#include <errno.h>           /* For O_* constants */

#include "queue.h"

#define MAP_FILE_NAME "/queue_test"
#define MAP_FILE_SIZE (100*1024*1024)    //100MB

char *gp_queue_buf; //100MB
char p_data[102400];

queue_t q;

int main(int argc, char **argv)
{
	int sharefd;
	int i = 0;	
	int ret;

	sharefd = shm_open(MAP_FILE_NAME, O_RDWR, 0);
	if (sharefd >= 0)
	{
		printf("shm_open() success.\n");
	}
	else
	{
		printf("shm_open() fail.errno:%d,strerror:%s\n", errno, strerror(errno));
		return -1;
	}

    if ( !ftruncate(sharefd, MAP_FILE_SIZE) )
	{
		printf("ftruncate() success.\n");
	}
	else
	{
		printf("ftruncate() fail.errno:%d,strerror:%s\n", errno, strerror(errno));
		return -1;
	}

	gp_queue_buf = mmap(NULL, MAP_FILE_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, sharefd, 0);	
	if (gp_queue_buf != MAP_FAILED)
	{
		printf("mmap() success.\n");
	}
	else
	{
		printf("mmap() fail.errno:%d,strerror:%s\n", errno, strerror(errno));
		return -1;
	}

	if (!queue_create(&q, gp_queue_buf, MAP_FILE_SIZE) )
	{
		printf("queue_create() success\n");
	}
	else
	{
		printf("queue_create() fail\n");
		return -1;
	}

	sleep(2);

	while (1)
	{
		i = 0;

		while (1)
		{
			ret = queue_read(&q, p_data, sizeof(p_data));
			if (ret>0)
			{
				printf("queue_read() success, p_data:%s, ret:%d\n", p_data, ret);
			}
			else
			{
				printf("queue_read() fail, p_data:%s,ret:%d\n", p_data, ret);
				sleep(1);
				break;
			}
			i++;

			if (i % 1000 == 0)
			{
				sleep(1);
			}
		}


		printf("----------------------------------\n");
		sleep(2);
	}	

	return 0;
}
